package logger

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func NewManticoreApi(ctx context.Context, endpoint, indexName string) *ManticoreApi {
	return &ManticoreApi{
		ctx:       ctx,
		endpoint:  endpoint,
		indexName: indexName,
	}
}

type ManticoreApi struct {
	ctx       context.Context
	endpoint  string
	indexName string
}

type LogEntry struct {
	Index     string `json:"index"`
	QueryType string `json:"query_type"`
	Query     string `json:"query"`
}

func (r *ManticoreApi) Log(message string) error {
	entry := LogEntry{
		Index:     r.indexName,
		QueryType: "insert",
		Query:     fmt.Sprintf(`{"message": "%s", "timestamp": %d}`, message, time.Now().Unix()),
	}

	body, err := json.Marshal(entry)
	if err != nil {
		return fmt.Errorf("failed to marshal log entry: %v", err)
	}

	resp, err := http.Post(r.getUrl("/insert"), "application/json", bytes.NewBuffer(body))
	if err != nil {
		return fmt.Errorf("failed to log to Manticore: %v", err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			panic(err)
		}
	}(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("error response from Manticore: %s", resp.Status)
	}

	return nil
}

func (r *ManticoreApi) getUrl(uri string) string {
	return fmt.Sprintf("%s%s", r.endpoint, uri)
}
